package com.example.servlet;

import com.example.util.DBUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;

@WebServlet("/import-quiz-sql")
@MultipartConfig
public class ImportQuizSqlServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part filePart = req.getPart("quizFile");
        String msg = null, err = null;
        if (filePart != null && filePart.getSize() > 0) {
            try (InputStream is = filePart.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                 Connection conn = DBUtil.getConnection();
                 Statement stmt = conn.createStatement()) {
                StringBuilder sqlBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    // 跳过注释和空行
                    if (line.trim().startsWith("--") || line.trim().isEmpty()) continue;
                    sqlBuilder.append(line).append("\n");
                    if (line.trim().endsWith(";")) {
                        String sql = sqlBuilder.toString();
                        stmt.execute(sql);
                        sqlBuilder.setLength(0);
                    }
                }
                msg = "题库SQL导入成功！";
            } catch (Exception e) {
                err = "导入失败：" + e.getMessage();
                e.printStackTrace();
            }
        } else {
            err = "请选择SQL文件！";
        }
        req.setAttribute("importMsg", msg);
        req.setAttribute("importErr", err);
        req.getRequestDispatcher("quiz-admin.jsp").forward(req, resp);
    }
} 